<?php

include_once "config.php";
if (!extension_loaded("pdo")) die("Missing PDO PHP extension."); // check if extension loaded
class DB {
	public $conn = NULL;
	public $err = NULL;
    public $dbname;
	public $hostname;
	public $dbusername;
	public $dbpassword;
	public $numofrows=0;
	public $affectedrows=0;
    public $portnumber=3306;
    public $dbtype="mysql";
	/**
	 * Connects to SQL Server
	 * 
	 * @return	true/false
	 */
   
   function __construct(){
        $this->dbname=DBNAME;
        $this->hostname=HOST;
        $this->dbusername=USERNAME;
        $this->dbpassword=PASSWORD;
        $this->dbtype=TYPE;
        $this->portnumber=PORTNUMBER;
   }
     
   public function connect()
	{
		// set OPTIONS
	    $options = array(
	        PDO::ATTR_PERSISTENT => true,
	        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
	    );
	    
        try {
			switch (strtolower($this->dbtype)) {
				case "mysql":
                    if (!extension_loaded("pdo_mysql")) die("Missing pdo_mysql PHP extension."); // check if extension loaded
					if(empty($this->portnumber)) $this->portnumber=3306;
                    //die("hostname: ".$this->hostname);
                    $this->conn = new PDO("mysql:host=".$this->hostname.";port=".$this->portnumber.";dbname=".$this->dbname, $this->dbusername, $this->dbpassword);
					break;
				
				case "pgsql":
					if (!extension_loaded("pdo_pgsql")) die("Missing pdo_pgsql PHP extension."); // check if extension loaded
					if(empty($this->portnumber)) $this->portnumber=5432;
					$this->conn = new PDO("pgsql:host=".$this->hostname.";port=".$this->portnumber.";dbname=".$this->dbname, $this->dbusername, $this->dbpassword);
					break;
					
				case "sqlite":
					if (!extension_loaded("pdo_sqlite")) die("Missing pdo_sqlite PHP extension."); // check if extension loaded	
					$this->rootdir = dirname(__FILE__)."/../../";
					$this->dbfile  = $this->rootdir."database/".$this->dbname.".db";
					$this->created = false;
					if(!file_exists($this->rootdir."database/")) {
						// try to create the database folder
						@mkdir($this->rootdir."database", 0777, true);			
					}
					if(!file_exists($this->dbfile)) {
						// try to create the database file
						if(@touch($this->dbfile))
							$this->created = true;
					}
					if(!file_exists($this->rootdir."database/.htaccess")) {
						// try to create the htaccess file
						@file_put_contents($this->rootdir."database/.htaccess", "Deny from all");
					}
					if(file_exists($this->dbfile) && is_readable($this->dbfile) && is_writable($this->dbfile)) {
						$this->conn = new PDO("sqlite:".$this->dbfile, $this->dbusername, $this->dbpassword);
						//if($this->created)
							//$this->conn->exec(file_get_contents($this->rootdir."sql/".$this->conf["server"]."/sqlite.sql"));
					} else {
						$this->err = "cant crate the sqlite database";
						return false;
					}
					break;
					
				default:
					$this->err = "not supported database type";
					return false;
					break;
			}
			return true;
		} catch (PDOException $e) {
			$this->err = $e->getMessage();
            die($e->getMessage());
			return false;
		}
		
	}
    
	
	
	/*
	 * close the database connection
	 */
	public function close () {
		$this->conn = NULL;
	}
	
	/**
	 * Sends a database query to SQL server.
	 *
	 * @param	string		$this->res 		a database query
	 * @param	array		$this->bind 		
	 * @return 	integer					id of the query result
	 */
	public function query($res, $bind = array()) {
		try {
			$query = Null;
			$query = $this->conn->prepare($res);
            
			if(is_array($bind) && !empty($bind))
            {
                $query->execute($bind);
			     
            }
            else
				$query->execute();
            
            $this->affectedrows=$query->rowCount();     
			
            return $query;
		} catch (PDOException $e) {
			$this->err = $e->getMessage();
            
		}
	}

	
	/**
	 * Gets a row from SQL database query result.
	 *
	 * @param	string		$this->res		a database query
	 * @return 				array		a row from result
	 */
	public function fetch_array ($res) {
		try {
            # Affected Rows?
			// 1
			$row = $res->fetchAll();
			
			for($i=0;$i<count($row);$i++)
			{
				foreach($row[$i] as $key=>$value)
				{
					$row[$i][$key]=trim(stripcslashes($value));
				}
			}
			return $row;
            
			//return $this->res->fetch(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			$this->err = $e->getMessage();
		}
	}
    
    public function fetch_num_of_rows ($res) {
		try {
            # Affected Rows?
			$this->affectedrows=$res->rowCount(); // 1
			$this->row = $res->fetchAll();
			
			for($i=0;$i<count($this->row);$i++)
			{
				foreach($this->row[$i] as $key=>$value)
				{
					$this->row[$i][$key]=trim(stripcslashes($value));
				}
			}
			return count($this->row);
            
			//return $res->fetch(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			$this->err = $e->getMessage();
		}
	}
	
	/**
	 * return the last insert id
	 */
	public function last_id () {
		return $this->conn->lastInsertId();
        
	}
	
	/**
	 * Returns SQL error number for last error.
	 *
	 * @return 	integer		MySQL error number
	 */
	public function error () {
		return $this->err;
	}
    
    public function updatecheckExistance($tablename,$conditionarr=array(),$idconditionarray=array())
    {
        $selectquery=$this->createSelectquerybasedonparams($tablename,$conditionarr);
        $bindarray=$this->getBindarray($conditionarr);
        if(count($idconditionarray)>0)
        {
            $selectquery.=" and id != :id";
            $bindarray[":id"]=$idconditionarray['id'];
        }
        $fetchinfo=$this->fetch_array($this->query($selectquery,$bindarray));
        if(count($fetchinfo)>0)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    
    public function checkExistance($tablename,$conditionarr=array())
    {
        $selectquery=$this->createSelectquerybasedonparams($tablename,$conditionarr);
        $bindarray=$this->getBindarray($conditionarr);
        $fetchinfo=$this->fetch_array($this->query($selectquery,$bindarray));
        if(count($fetchinfo)>0)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    
    public function insertData($tablename,$fieldarray=array())
    {
        $insertquery=$this->createInsertquerybasedonparams($tablename,$fieldarray);
        $bindarray=$this->getBindarray($fieldarray);
        
        $this->query($insertquery,$bindarray);
    }
    
    public function updateData($tablename,$fieldarray=array(),$conditionarray=array())
    {
        $updatequery=$this->createUpdatequerybasedonparams($tablename,$fieldarray,$conditionarray);
        $resultarray = array_merge($fieldarray, $conditionarray);
        $bindarray=$this->getBindarray($resultarray);
        
        $this->query($updatequery,$bindarray);
    }
    
    
    public function deleteData($tablename,$conditionarray=array())
    {
        $deletequery=$this->createDeletebasedonparams($tablename,$conditionarray);
        $bindarray=$this->getBindarray($conditionarray);
        $this->query($deletequery,$bindarray);
    }
    public function createSelectquerybasedonparams($tables="users",$fieldarray=array(),$fields='id')
    {
        $sqlquery="select ".$fields." from ".$tables;
        if(count($fieldarray)>0)
        {
            $sqlquery.=" where ";
            foreach($fieldarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key." and ";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-4);
        }
        return $sqlquery;
    }
    
    public function createInsertquerybasedonparams($tables="users",$fieldarray=array())
    {
        $sqlquery="insert into ".$tables." set ";
        if(count($fieldarray)>0)
        {
            foreach($fieldarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key.",";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-1);
        }
        return $sqlquery;
    }
    
    public function getBindarray($fieldarray=array())
    {
        $bindarray=array();
        foreach($fieldarray as $key=>$value)
    	{
    		$bindarray[":".$key]=$value;
    	}
        return $bindarray;
    }
    
    public function createUpdatequerybasedonparams($tables="users",$fieldarray=array(),$conditionarray=array())
    {
        $sqlquery="update ".$tables." set ";
        if(count($fieldarray)>0)
        {
            foreach($fieldarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key.",";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-1);
        }
        if(count($conditionarray)>0)
        {
            $sqlquery.=" where ";
            foreach($conditionarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key." and ";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-4);
        }
        
        return $sqlquery;
    }
    
    public function createDeletebasedonparams($tables="users",$conditionarray=array())
    {
        $sqlquery="delete from ".$tables." ";
        if(count($conditionarray)>0)
        {
            $sqlquery.=" where ";
            foreach($conditionarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key." and ";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-4);
        }
        
        return $sqlquery;
    }
    
}
?>
